<template>
    <rui-page :defines="defines">
        <rui-query :label-width="150"
                   ref="searchForm"
                   :query="queryData"
                   :query-rows="searchFormOptions"
        />
        <Row>
            <Alert show-icon>
                已选择 <span class="select-count">{{selectCount}}</span> 项
                <a class="select-clear" @click="clearSelectAll">清空</a>
            </Alert>
        </Row>
        <rui-table
            :defineId="'defineExtrasTable'"
            :fixedLeft="['action']"
            :showIndex="false"
            :select="true"
            :slots="[{key:'action',slot:'action'},{key:'isEnable',slot:'isEnable'}]"
            @loadDatas="queryData"
            ref-query="searchForm"
            @on-selection-change="changeSelect"
            ref="extrasTable"
        >
            <template slot="toolBar">
                <Button @click="add" icon="md-add" type="primary">新增</Button>
                <Button @click="enableAll" type="primary">有效</Button>
                <Button @click="DisableAll" type="primary">无效</Button>
            </template>
            <template slot="action" slot-scope="{ row }">
                <div>
                    <Button @click="edit(row)" size="small" type="primary" :disabled="row.isEnable!='0'">编辑</Button>
                    <!--<Button @click="view(row)" size="small" type="primary" v-if="row.isEnable=='1'">查看</Button>-->
                    <Button type="error" size="small" @click="remove(row)" :disabled="row.isEnable!='0'">删除</Button>
                </div>
            </template>
            <template slot-scope="{ row, index }" slot="isEnable">
                <div>
                    <tag v-if="row.isEnable=='1'" color="success" size="default">有效</tag>
                    <tag v-if="row.isEnable=='0'" color="error" size="default">无效</tag>
                </div>
            </template>
        </rui-table>
        <Modal
            v-model="extrasModalVisible"
            :title="modalTitle"
            :width="800"
            :closable="false"
            :mask-closable="false"
            @on-ok="extrasSubmit"
        >
            <rui-form :form-options="extrasFormOptions" :after-change="afterChange" :read-only="false" ref="extrasForm">
                <template slot="fatherName" slot-scope="{ key,data }">
                    <span>
                         <Select v-model="data[key]" style="width:200px" filterable remote>
                            <Option v-for="item in locationData" :value="item.value" :key="item.value">{{ item.label }}</Option>
                             <Page v-show="locationData.length>0" :page-size="pageData.pageSize" :total="pageData.total" @on-change="changeBasePage" style="text-align: center;" simple />
                        </Select>
                    </span>
                </template>
            </rui-form>
            <div slot="footer">
                <Button size="small" @click="extrasModalVisible = false">取消</Button>
                <Button type="primary" size="small" @click="extrasSubmit" v-show="op!='view'">保存</Button>
            </div>
        </Modal>
    </rui-page>
</template>
<script>
    import defineExtras from "./define/extras-define";
    import defineExtrasForm from "./define/extras-form-define";
    import defineExtrasTable from "./define/extras-table-define";
    import {
        getExtrasListData,
        addExtras,
        deleteExtras,
        enableExtras,
        disableExtras,
        getSelectFatherNo
    } from "@/projects/afs-core-business/api/afs-product/product/extrasProject";
    import {
        deepClone
    } from "@/libs/utils/ObjectClone";

    export default {
        name: "extras-project",
        data() {
            return {
                locationData: [],
                extrasModalVisible: false,
                modalTitle: "附加贷项目新增",
                searchFormOptions: [
                    {defineId: "defineExtras", span: 12, fields: ["extrasProjectNo", "extrasProjectName","isEnable", "isExistsFather"]},
                ],
                extrasFormOptions: [
                    {
                        grids: [
                            {
                                defineId: "defineExtrasForm",
                                span: 12,
                                fields: ["extrasProjectNo", "isEnable", "fatherNo"],
                                slots: [{key: 'fatherNo', slotName: 'fatherName'}]
                            },
                            {
                                defineId: "defineExtrasForm",
                                span: 12,
                                fields: ["extrasProjectName", "isExistsFather"],
                            }
                        ]
                    }
                ],
                selectCount: 0,
                //状态判断
                op:'view',
                //父集分页
                pageData: {
                    pageNumber: 1,
                    pageSize: 5,
                    total: 0
                },
            };
        },
        computed: {
            defines() {
                return [
                    {
                        id: "defineExtras",
                        fields: defineExtras
                    },
                    {
                        id: "defineExtrasTable",
                        fields: defineExtrasTable
                    },
                    {
                        id: "defineExtrasForm",
                        fields: defineExtrasForm
                    }
                ];
            }
        },
        methods: {


            //页码变化
            changeBasePage(value){
                this.pageData.pageNumber = value;
                this.selectFatherNoListData();
            },
            selectFatherNoListData() {
                getSelectFatherNo(this.pageData).then(res => {
                    if (res.code === "0000") {
                        this.locationData = res.data.records;
                        this.pageData.total = res.data.total;
                    }
                });
            },
            queryData(queryData) {
                getExtrasListData(queryData).then(res => {
                    if (res.code === "0000") {
                        let {records, total} = res.data;
                        this.$refs.extrasTable.updateTableData(records, total);
                    }
                });
            },
            refresh() {
                this.$refs['extrasTable'].reloadData();
                this.clearSelectAll();
            },
            clearSelectAll() {
                this.$refs.extrasTable.getTable().selectAll(false);
            },
            extrasSubmit() {
                this.$refs.extrasForm.getForm().validate(valid => {
                    if (valid) {
                        if (this.modalType === 0) {
                            addExtras(this.$refs.extrasForm.getFormData())
                                .then(res => {
                                    if (res.code === "0000") {
                                        this.$Message.success(res.msg);
                                        this.refresh();
                                        this.selectFatherNoListData();
                                        this.extrasModalVisible = false;
                                    }
                                })
                                .catch(() => {
                                    this.refresh();
                                });
                        } else {
                            // 编辑
                            addExtras(this.$refs.extrasForm.getFormData())
                                .then(res => {
                                    if (res.code === "0000") {
                                        this.$Message.success(res.msg);
                                        this.refresh();
                                        this.selectFatherNoListData();
                                        this.extrasModalVisible = false;
                                    }
                                })
                                .catch(() => {
                                    this.refresh();
                                });
                        }
                    }
                });
            },
            remove(v) {
                this.$Modal.confirm({
                    title: "确认删除",
                    content: "您确认要删除编号 " + v.extrasProjectNo + " ?",
                    onOk: () => {
                        deleteExtras(v.id).then(res => {
                            if (res.code === "0000") {
                                this.$Message.success(res.msg);
                                this.refresh();
                            }
                        });
                    }
                });
            },
            changeSelect(e) {
                this.selectList = e;
                this.selectCount = e.length;
            },
            enableAll() {
                if (this.selectCount <= 0 || this.selectCount == undefined) {
                    this.$Message.warning("您还未选择数据");
                    return;
                }
                if (this.check("effective")) {
                    return;
                }
                this.$Modal.confirm({
                    title: "确认生效",
                    onOk: () => {
                        let ids = [];
                        this.selectList.forEach(function (e) {
                            ids += e.id + ",";
                        });
                        ids = ids.substring(0, ids.length - 1);
                        enableExtras(ids).then(res => {
                            if (res.code === "0000") {
                                this.$Message.success("操作成功");
                                this.refresh();
                            }
                        });
                    }
                });
            },
            DisableAll() {
                if (this.selectCount <= 0 || this.selectCount == undefined) {
                    this.$Message.warning("您还未选择数据");
                    return;
                }
                if (this.check("invalid")) {
                    return;
                }
                this.$Modal.confirm({
                    title: "确认失效",
                    onOk: () => {
                        let ids = [];
                        this.selectList.forEach(function (e) {
                            ids += e.id + ",";
                        });
                        ids = ids.substring(0, ids.length - 1);
                        disableExtras(ids).then(res => {
                            if (res.code === "0000") {
                                this.$Message.success("操作成功");
                                this.refresh();
                            }
                        });
                    }
                });
            },
            check(type) {
                let invalidNum = 0;
                let effectiveNum = 0;
                this.selectList.forEach((e) => {
                    if (e.isEnable == 0) {//无效
                        invalidNum++;
                    } else if (e.isEnable == 1) {//有效
                        effectiveNum++;
                    }
                });
                console.info("有效:"+effectiveNum,"无效"+invalidNum);
                var checkResult = false;
                if ("invalid" == type && invalidNum > 0) {
                    this.$Message.warning("不可设置无效数据为无效！");
                    checkResult = true;
                }
                if ("effective" == type && effectiveNum > 0) {
                    this.$Message.warning("不可设置有效数据为有效！");
                    checkResult = true;
                }
                return checkResult;
            },
            afterChange(key, newValue) {
                if (key == 'isExistsFather' && newValue == "0") {
                    this.$refs.extrasForm.setFiledValue('fatherNo', '');
                    this.$refs.extrasForm.setFiledHide('fatherNo', true);
                } else if (key == 'isExistsFather') {
                    this.$refs.extrasForm.setFiledHide('fatherNo', false);
                }
            },
            add() {
                this.modalType = 0;
                this.modalTitle = "新增";
                this.$refs.extrasForm.setAllFieldReadOnly(false);
                this.$refs.extrasForm.setAllFieldRequired(true);
                this.$nextTick(() => {
                    this.$refs.extrasForm.resetFrom();
                    this.$refs.extrasForm.setFiledValue('isExistsFather', '0');
                });
                this.extrasModalVisible = true;
                this.op='add';
            },
            edit(row) {
                this.modalType = 1;
                this.modalTitle = "编辑";
                this.$refs.extrasForm.updateFormData(deepClone(row));
                this.$refs.extrasForm.setAllFieldReadOnly(false);
                // this.$refs.extrasForm.setFieldReadOnly('extrasProjectNo', true);
                this.$refs.extrasForm.setAllFieldRequired(true);
                this.extrasModalVisible = true;
                this.op='edit';
            },
            view(row) {
                this.modalTitle = "查看";
                this.$refs.extrasForm.updateFormData(deepClone(row));
                this.$refs.extrasForm.setAllFieldRequired(false);
                this.$refs.extrasForm.setAllFieldReadOnly(true);
                this.extrasModalVisible = true;
                this.op='view';
            }
        },
        mounted() {
            this.selectFatherNoListData();
            this.refresh();
        }
    };
</script>
